﻿namespace NebulaServer.Core
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel.Composition;
    using System.ComponentModel.Composition.Hosting;
    using System.IO;
    using System.Linq;
    using System.Reflection;
    using System.Web;
    using System.Web.Mvc;
    using System.Web.Routing;
    using System.Web.SessionState;
    using NebulaServer.Config;

    public class MefControllerFactory : IControllerFactory
    {
        private IConfig config;
        private IComposition composition;

        public MefControllerFactory(string pluginPath)
        {
            this.config = new ConfigQuery();
            this.composition = new MefComposition();
            this.composition.Compose(pluginPath);
        }

        public virtual IController CreateController(RequestContext requestContext, string controllerName)
        {
            if (controllerName != this.config.Get<string>("ExceptFavicon"))
            {
                return this.composition.GetLazyExportValue<IController>(controllerName);
            }

            return default(IController);
        }

        public virtual void ReleaseController(IController controller)
        {
            var disposable = (IDisposable)controller;
            if (disposable != null)
            {
                disposable.Dispose();
            }
        }

        public virtual SessionStateBehavior GetControllerSessionBehavior(RequestContext requestContext, string controllerName)
        {
            return SessionStateBehavior.Default;
        }
    }
}
